import java.util.Scanner;
import java.util.Map;
public class ShoppingSystem {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Store store = new Store();

        // 初始化数据
        Admin admin = new Admin("admin", "dlgq926494@");

        while (true) {
            System.out.println("\n请选择登录类型：");
            System.out.println("1. 管理员登录");
            System.out.println("2. 客户登录");
            System.out.println("3. 客户注册");
            System.out.println("4. 退出");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 清除缓冲区的换行符

            switch (choice) {
                case 1:
                    adminLogin(scanner, store, admin);
                    break;
                case 2:
                    customerLogin(scanner, store);
                    break;
                case 3:
                    customerRegistration(scanner, store);
                    break;
                case 4:
                    System.out.println("退出系统。");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private static void adminLogin(Scanner scanner, Store store, Admin admin) {
        System.out.print("请输入用户名：");
        String username = scanner.nextLine();
        System.out.print("请输入密码：");
        String password = scanner.nextLine();

        if (admin.getUsername().equals(username) && admin.getPassword().equals(password)) {
            System.out.println("管理员登录成功！");
            adminMenu(scanner, store, admin);
        }
        else {
            System.out.println("用户名或密码错误！");
        }
    }


    private static void customerLogin(Scanner scanner, Store store) {
        System.out.print("请输入用户名：");
        String username = scanner.nextLine();
        System.out.print("请输入密码：");
        String password = scanner.nextLine();

        Customer customer = store.getCustomers().stream()
                .filter(c -> c.getUsername().equals(username) && c.getPassword().equals(password))
                .findFirst().orElse(null);

        if (customer != null) {
            System.out.println("客户登录成功！");
            customerMenu(scanner, store, customer);
        } else {
            System.out.println("用户名或密码错误！");
        }
    }

    private static void customerRegistration(Scanner scanner, Store store) {
        System.out.print("请输入用户名：");
        String username = scanner.nextLine();

        System.out.print("请输入密码（必须包含大小写字母、数字和标点符号，长度大于8）：");
        String password = scanner.nextLine();

        System.out.print("请输入手机号码：");
        String phoneNumber = scanner.nextLine();

        System.out.print("请输入电子邮箱：");
        String email = scanner.nextLine();

        if (password.length() > 8 && password.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]+$")) {
            Customer customer = new Customer(username, password, phoneNumber, email);
            store.addCustomer(customer);
            System.out.println("注册成功！");
        } else {
            System.out.println("密码不符合要求，请重新注册。");
        }
    }

    private static void adminMenu(Scanner scanner, Store store, Admin admin) {
        while (true) {
            System.out.println("\n管理员菜单：");
            System.out.println("1. 列出所有客户信息");
            System.out.println("2. 删除客户信息");
            System.out.println("3. 查询客户信息");
            System.out.println("4. 列出所有商品信息");
            System.out.println("5. 添加商品信息");
            System.out.println("6. 修改商品信息");
            System.out.println("7. 删除商品信息");
            System.out.println("8. 修改管理员密码");
            System.out.println("9. 重置客户密码");
            System.out.println("10. 退出登录");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    store.getCustomers().forEach(System.out::println);
                    break;
                case 2:
                    System.out.print("请输入要删除的客户ID：");
                    String customerIdToDelete = scanner.nextLine();
                    Customer customerToDelete = store.getCustomers().stream()
                            .filter(c -> c.getId().equals(customerIdToDelete))
                            .findFirst().orElse(null);
                    if (customerToDelete != null) {
                        System.out.println("确认删除该客户信息？（Y/N）");
                        String confirm = scanner.nextLine();
                        if (confirm.equalsIgnoreCase("Y")) {
                            store.getCustomers().remove(customerToDelete);
                            System.out.println("客户信息已删除。");
                        }
                    } else {
                        System.out.println("未找到该客户。");
                    }
                    break;
                case 3:
                    System.out.print("请输入客户ID或用户名：");
                    String query = scanner.nextLine();
                    store.getCustomers().stream()
                            .filter(c -> c.getId().equals(query) || c.getUsername().equals(query))
                            .forEach(System.out::println);
                    break;
                case 4:
                    store.listAllProducts();
                    break;
                case 5:
                    addProduct(scanner, store);
                    break;
                case 6:
                    modifyProduct(scanner, store);
                    break;
                case 7:
                    System.out.print("请输入要删除的商品编号：");
                    String productIdToDelete = scanner.nextLine();
                    Product productToDelete = store.findProductById(productIdToDelete);
                    if (productToDelete != null) {
                        System.out.println("确认删除该商品信息？（Y/N）");
                        String confirm = scanner.nextLine();
                        if (confirm.equalsIgnoreCase("Y")) {
                            store.removeProduct(productToDelete);
                            System.out.println("商品信息已删除。");
                        }
                    } else {
                        System.out.println("未找到该商品。");
                    }
                    break;
                case 8:
                    admin.changePassword(scanner);
                    break;
                case 9: System.out.print("请输入要重置密码的客户用户名：");
                    String customerUsername = scanner.nextLine();
                    Customer customer = store.findCustomerByUsername(customerUsername);
                    if (customer != null) {
                        admin.resetCustomerPassword(customer);
                    } else {
                        System.out.println("未找到客户。");
                    }
                    break;
                case 10:
                    System.out.println("退出管理员登录。");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private static void addProduct(Scanner scanner, Store store) {
        System.out.print("请输入商品编号：");
        String id = scanner.nextLine();

        System.out.print("请输入商品名称：");
        String name = scanner.nextLine();

        System.out.print("请输入生产厂家：");
        String manufacturer = scanner.nextLine();

        System.out.print("请输入生产日期（格式：YYYY-MM-DD）：");
        String productionDate = scanner.nextLine();

        System.out.print("请输入型号：");
        String model = scanner.nextLine();

        System.out.print("请输入进货价：");
        double purchasePrice = scanner.nextDouble();

        System.out.print("请输入零售价：");
        double retailPrice = scanner.nextDouble();

        System.out.print("请输入数量：");
        int quantity = scanner.nextInt();
        scanner.nextLine();

        Product product = new Product(id, name, manufacturer, productionDate, model, purchasePrice, retailPrice, quantity);
        store.addProduct(product);
        System.out.println("商品信息添加成功！");
    }

    private static void modifyProduct(Scanner scanner, Store store) {
        System.out.print("请输入要修改的商品编号：");
        String productId = scanner.nextLine();

        Product product = store.findProductById(productId);
        if (product != null) {
            System.out.print("请输入新的商品名称（留空表示不修改）：");
            String newName = scanner.nextLine();
            if (!newName.isEmpty()) {
                product.setName(newName);
            }

            System.out.print("请输入新的生产厂家（留空表示不修改）：");
            String newManufacturer = scanner.nextLine();
            if (!newManufacturer.isEmpty()) {
                product.setManufacturer(newManufacturer);
            }

            System.out.print("请输入新的生产日期（格式：YYYY-MM-DD，留空表示不修改）：");
            String newProductionDate = scanner.nextLine();
            if (!newProductionDate.isEmpty()) {
                product.setProductionDate(newProductionDate);
            }

            System.out.print("请输入新的型号（留空表示不修改）：");
            String newModel = scanner.nextLine();
            if (!newModel.isEmpty()) {
                product.setModel(newModel);
            }

            System.out.print("请输入新的进货价（留空表示不修改）：");
            String purchasePriceInput = scanner.nextLine();
            if (!purchasePriceInput.isEmpty()) {
                double newPurchasePrice = Double.parseDouble(purchasePriceInput);
                product.setPurchasePrice(newPurchasePrice);
            }

            System.out.print("请输入新的零售价（留空表示不修改）：");
            String retailPriceInput = scanner.nextLine();
            if (!retailPriceInput.isEmpty()) {
                double newRetailPrice = Double.parseDouble(retailPriceInput);
                product.setRetailPrice(newRetailPrice);
            }

            System.out.print("请输入新的数量（留空表示不修改）：");
            String quantityInput = scanner.nextLine();
            if (!quantityInput.isEmpty()) {
                int newQuantity = Integer.parseInt(quantityInput);
                product.setQuantity(newQuantity);
            }

            System.out.println("商品信息修改成功！");
        } else {
            System.out.println("未找到该商品。");
        }
    }

    private static void customerMenu(Scanner scanner, Store store, Customer customer) {
        ShoppingCart cart = new ShoppingCart();
        while (true) {
            System.out.println("\n客户菜单：");
            System.out.println("1. 将商品加入购物车");
            System.out.println("2. 将商品从购物车中移除");
            System.out.println("3. 修改购物车中的商品数量");
            System.out.println("4. 结账");
            System.out.println("5. 查看购物历史");
            System.out.println("6. 修改密码");
            System.out.println("7. 退出登录");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    System.out.print("请输入商品编号：");
                    String productId = scanner.nextLine();
                    Product product = store.findProductById(productId);
                    if (product != null) {
                        System.out.print("请输入数量：");
                        int quantity = scanner.nextInt();
                        scanner.nextLine();
                        cart.addProduct(product, quantity);
                        System.out.println("商品已加入购物车！");
                    } else {
                        System.out.println("未找到该商品。");
                    }
                    break;
                case 2:
                    System.out.print("请输入要移除的商品编号：");
                    String productIdToRemove = scanner.nextLine();
                    Product productToRemove = store.findProductById(productIdToRemove);
                    if (productToRemove != null) {
                        System.out.println("确认移除该商品？（Y/N）");
                        String confirm = scanner.nextLine();
                        if (confirm.equalsIgnoreCase("Y")) {
                            cart.removeProduct(productToRemove);
                            System.out.println("商品已从购物车中移除。");
                        }
                    } else {
                        System.out.println("未找到该商品。");
                    }
                    break;
                case 3:
                    System.out.print("请输入要修改的商品编号：");
                    String productIdToUpdate = scanner.nextLine();
                    Product productToUpdate = store.findProductById(productIdToUpdate);
                    if (productToUpdate != null) {
                        System.out.print("请输入新的数量：");
                        int newQuantity = scanner.nextInt();
                        scanner.nextLine();
                        cart.updateProductQuantity(productToUpdate, newQuantity);
                        System.out.println("购物车中商品数量已更新。");
                    } else {
                        System.out.println("未找到该商品。");
                    }
                    break;
                case 4:
                    checkout(scanner, store, customer, cart);
                    break;
                case 5:
                    viewShoppingHistory(customer);
                    break;
                case 6:
                    changeCustomerPassword(scanner, customer);
                    break;
                case 7:
                    System.out.println("退出客户登录。");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private static void checkout(Scanner scanner, Store store, Customer customer, ShoppingCart cart) {
        double totalAmount = cart.getTotalAmount();
        if (totalAmount == 0) {
            System.out.println("购物车为空，无法结账。");
            return;
        }

        System.out.println("请选择支付方式：");
        System.out.println("1. 支付宝");
        System.out.println("2. 微信");
        System.out.println("3. 银行卡");
        int paymentChoice = scanner.nextInt();
        scanner.nextLine();

        // 模拟支付操作（这里只是简单地输出提示信息）
        System.out.println("正在处理支付...");
        switch (paymentChoice) {
            case 1:
                System.out.println("使用支付宝支付成功！");
                break;
            case 2:
                System.out.println("使用微信支付成功！");
                break;
            case 3:
                System.out.println("使用银行卡支付成功！");
                break;
            default:
                System.out.println("无效的支付方式，支付失败。");
                return;
        }

        // 支付成功后更新库存并记录购买历史
        for (Map.Entry<Product, Integer> entry : cart.getItems().entrySet()) {
            Product product = entry.getKey();
            int quantityPurchased = entry.getValue();
            product.setQuantity(product.getQuantity() - quantityPurchased);
            customer.addPurchase(product.getName(), product.getRetailPrice() * quantityPurchased);
        }

        // 清空购物车
        cart.clearCart();
        System.out.println("结账成功，购物车已清空。");
    }

    private static void viewShoppingHistory(Customer customer) {
        System.out.println("您的购物历史：");
        if (customer.getShoppingHistory().isEmpty()) {
            System.out.println("没有购物记录。");
        } else {
            customer.getShoppingHistory().forEach(System.out::println);
        }
    }

    private static void changeCustomerPassword(Scanner scanner, Customer customer) {
        System.out.print("请输入当前密码：");
        String currentPassword = scanner.nextLine();

        if (!currentPassword.equals(customer.getPassword())) {
            System.out.println("当前密码错误。");
            return;
        }

        System.out.print("请输入新密码（必须包含大小写字母、数字和标点符号，长度大于8）：");
        String newPassword = scanner.nextLine();

        if (newPassword.length() > 8 && newPassword.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]+$")) {
            customer.setPassword(newPassword);
            System.out.println("密码修改成功！");
        } else {
            System.out.println("新密码不符合要求，请重试。");
        }
    }
}